class IndexedDB {
	constructor(dbName, storeName, version) {
		this.storeName = storeName
		const indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB
		const request = indexedDB.open(dbName, version)

		request.onsuccess = e => {
			this.db = e.target.result
			console.log('indexDB initialization successful')
		}
		request.onupgradeneeded = e => {
			this.db = e.target.result
			if (!this.db.objectStoreNames.contains(storeName)) {
				this.store = this.db.createObjectStore(storeName)
			}
			console.log('Database created successfully,Version：' + version)
		}
		request.onerror = e => {
			console.info('Database creation failed', e)
		}
	}
	get(key, callback) {
		const transaction = this.db.transaction(this.storeName)
		const objectStore = transaction.objectStore(this.storeName)
		const request = objectStore.get(key)

		request.onerror = e => {
			console.info('Get failed', e)
		}
		request.onsuccess = e => {
			callback(e.target.result)
		}
	}
	set(key, value) {
		let oldValue
		this.get(key, function (res) {
			oldValue = res
		})

		if (oldValue) {
			console.info('Please use the update method to update!')
		} else {
			const transaction = this.db.transaction(this.storeName, 'readwrite')
			const objectStore = transaction.objectStore(this.storeName)
			const request = objectStore.add(value, key)

			request.onerror = e => {
				console.info('Add failed', e)
			}
		}
	}
	update(newValue, key) {
		const oldValue = this.get(key)

		if (!oldValue) {
			console.info('You should use function set')
		} else {
			const transaction = this.db.transaction(this.storeName, 'readwrite')
			const objectStore = transaction.objectStore(this.storeName)
			const request = objectStore.put(newValue, key)

			request.onerror = e => {
				console.info('Update failed', e)
			}
		}
	}
	remove(key) {
		const request = this.db
			.transaction(this.storeName, 'readwrite')
			.objectStore(this.storeName)
			.delete(key)
		request.onerror = e => {
			console.info('Failed to delete', e)
		}
	}
	delete(name) {
		window.indexedDB.deleteDatabase(name)
	}
	close() {
		this.db.close()
	}
}

export default IndexedDB
